package com.boot.proofing.controller.business;/**
 * @description
 * @autor xbwu on 2017/8/9.
 */

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.core.common.base.ResultWapper;
import com.boot.core.common.util.LocaleMessageSource;
import com.boot.proofing.common.config.WebSecurityConfig;
import com.boot.proofing.common.util.EncryptUtils;
import com.boot.proofing.common.util.FileUtil;
import com.boot.proofing.common.util.WebUtils;
import com.boot.proofing.controller.base.BaseController;
import com.boot.proofing.mpweb.base.entity.User;
import com.boot.proofing.mpweb.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户入口
 *
 * @author xbwu
 * @create 2017-08-09
 **/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    IUserService userService;
    @Autowired
    private LocaleMessageSource i18n;


    @GetMapping(value = "/getUserListLike")
    public ResultWapper getUserListLike(Page<User> page, String keyword){
        ResultWapper rw = null;
        do {
            rw=ResultWapper.success();
            rw.addResult("pages", userService.selectLikeForPage(page, keyword));
        } while (false);
        return rw;
    }

    @GetMapping(value = "/getUserDetail")
    public ResultWapper getUserDetail(String userId){
        ResultWapper rw = null;
        do {
            rw=ResultWapper.success();
            rw.addResult("user", userService.getById(userId));
        } while (false);
        return rw;
    }
    @GetMapping(value = "/getCurrentUserDetail")
    public ResultWapper getCurrentUserDetail(){
        ResultWapper rw = null;
        do {
            rw=ResultWapper.success();
            rw.addResult("user", userService.getCurrentUser());
        } while (false);
        return rw;
    }

    @PostMapping(value = "/userInsertOrUpdate")
    public ResultWapper userInsertOrUpdate(User user){
        ResultWapper rw = null;
        do {
            Boolean result=userService.saveOrUpdate(user);
            if(result){
                rw=ResultWapper.success();
            }else{
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
        } while (false);
        return rw;
    }

    @PostMapping(value = "/userSelfUpdate")
    public ResultWapper userSelfUpdate(User user,HttpServletRequest request){
        ResultWapper rw = null;
        do {
            User oldUser=userService.getById(user.getId());
            if(!userService.getCurrentUser().getId().equals(user.getId())){
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
            //避免恶意修改账号
            user.setAccount(null);
            //避免恶意修改用户类型
            user.setUserType(null);
            //存在头像且不相同则移除旧头像
            if(user.getHeadPath()!=null&&!userService.headIsEquals(user.getId(),user.getHeadPath())){
                FileUtil.removeFile(oldUser.getFullHeadPath());
            }
            Boolean result=userService.updateById(user);
            if(result){
                rw=ResultWapper.success();
                WebUtils.setSessionAttribute(request, WebSecurityConfig.USER,userService.getById(user.getId()));
            }else{
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
        } while (false);
        return rw;
    }

    @PostMapping(value = "/userSelfChangePassword")
    public ResultWapper userSelfChangePassword(String oldPassword,
            String newPassword){
        ResultWapper rw = null;
        do {
            //重复修改密码不清楚缓存则密码不会变，强制获取最新密码
            User u=userService.getById(userService.getCurrentUser().getId());
            if(u==null){
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
                break;
            }
            if(!EncryptUtils.encryptPassword(oldPassword).equals(u.getPassword())){
                rw=ResultWapper.error(i18n.getMsg("login.oldPassword.error"));
                break;
            }
            Boolean result=userService.updatePasswordById(u.getId(),newPassword);
            if(result){
                rw=ResultWapper.success();
            }else{
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
        } while (false);
        return rw;
    }

    /**
     * 修改状态
     * @param userId
     * @param valid
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/userStatusChange")
    public ResultWapper userStatusChange(Long userId,Boolean valid){
        ResultWapper rw = null;
        do {
            User u=new User();
            u.setId(userId);
            u.setValid(valid);
            Boolean result=userService.updateById(u);
            if(result){
                rw=ResultWapper.success();
            }else{
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
        } while (false);
        return rw;
    }


    @PostMapping(value = "/userDelete")
    public ResultWapper userDelete(@RequestParam Map<String, Object> param){
        ResultWapper rw = null;
        do {
            List<Long> list=new ArrayList<>();
            if(!param.containsKey("userIds")&& !param.containsKey("userIds[]")){
                rw=ResultWapper.error(i18n.getMsg("system.error.param.error"));
                break;
            }
            String userIds=(String)(param.containsKey("userIds")?param.get("userIds"):param.get("userIds[]"));
            for(String userId:userIds.split(",")){
                list.add(Long.valueOf(userId));
            }
            Boolean result=userService.removeByIds(list);
            if(result){
                rw=ResultWapper.success();
            }else{
                rw=ResultWapper.error(i18n.getMsg("system.error.operate"));
            }
        } while (false);
        return rw;
    }
}